﻿using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Helper
{
    /// <summary>
    /// MailKit辅助类
    /// </summary>
    public class MailKitHelper
    {
        private static string host = "smtp.exmail.qq.com"; //smtp服务器地址
        private static string emailUserName = "zhangdeng@zhiyuanhui.com";//发件人邮箱
        private static string emailAddressName = "zhangdeng@zhiyuanhui.com"; //发件人姓名
        private static string emailPassword = "Aa287572291"; //密码

        #region 发送邮件

        /// <summary>
        /// 同步发送邮件
        /// </summary>
        /// <param name="email">收件人邮箱地址</param>
        /// <param name="subject">标题</param>
        /// <param name="message">内容</param>
        /// <param name="textpart">内容格式(默认为p:plain)，不写为html</param>
        /// <returns></returns>
        public static bool SendEmail(string email, string subject, string message, string textpart = "p")
        {
            textpart = textpart == "p" ? "plain" : "html";
            try
            {
                var emailMessage = new MimeMessage();
                emailMessage.From.Add(new MailboxAddress(emailAddressName, emailUserName));
                string[] emailArray = email.Split(',');
                foreach (var item in emailArray)
                {
                    emailMessage.To.Add(new MailboxAddress(item));
                }
                emailMessage.Subject = subject;
                emailMessage.Body = new TextPart(textpart) { Text = message };
                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect(host, 465, SecureSocketOptions.Auto);
                    client.Authenticate(emailUserName, emailPassword);
                    client.Send(emailMessage);
                    client.Disconnect(true);
                }
                return true;
            }
            catch (Exception ex)
            {              
                Common.Helper.Logger.Info($"SendEmail-发送邮件异常,异常信息{ex.ToString()}");
                return false;
            }
        }

        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="email">收件人邮箱地址</param>
        /// <param name="subject">标题</param>
        /// <param name="message">内容</param>
        /// <param name="textpart">内容格式(默认为p:plain)，不写为html</param>
        /// <returns></returns>
        public static async Task<bool> SendEmailAsync(string email, string subject, string message, string textpart = "p")
        {
            textpart = textpart == "p" ? "plain" : "html";
            try
            {
                var emailMessage = new MimeMessage();
                emailMessage.From.Add(new MailboxAddress(emailAddressName, emailUserName));

                emailMessage.To.Add(new MailboxAddress("mail", email));
                emailMessage.Subject = subject;
                emailMessage.Body = new TextPart(textpart) { Text = message };

                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(host, 25, SecureSocketOptions.None).ConfigureAwait(false);
                    await client.AuthenticateAsync(emailUserName, emailPassword);
                    await client.SendAsync(emailMessage).ConfigureAwait(false);
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
                return true;
            }
            catch (Exception ex)
            {             
                Common.Helper.Logger.Info($"SendEmailAsync-发送邮件异常,异常信息{ex.ToString()}");
                return false;
            }
        }

        /// <summary>
        /// 异步发送邮件并抄送
        /// </summary>
        /// <param name="email">收件人列表</param>
        /// <param name="ccemail"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="textpart"></param>
        /// <returns></returns>

        public static async Task<bool> BatchSendEmailAsync(string email, string ccemail, string subject, string message, int reportid, List<byte[]> attachments = null, string textpart = "p")
        {
            textpart = textpart == "p" ? "plain" : "html";
            try
            {
                //实例化
                var emailMessage = new MimeMessage();

                //发件人邮箱  名称
                emailMessage.From.Add(new MailboxAddress(emailAddressName, emailUserName));

                //收件人
                string[] emailArray = email.Split(',');
                foreach (var item in emailArray)
                {
                    if (item.Trim()!="")
                    {
                        emailMessage.To.Add(new MailboxAddress(item));
                    }
                }

                //抄送人
                string[] ccemailArray = ccemail.Split(',');
                foreach (var item in ccemailArray)
                {
                    if (item.Trim() != "")
                    {
                        emailMessage.Cc.Add(new MailboxAddress(item));
                    }
                }

                //主题
                emailMessage.Subject = subject;

                //附件集合
                List<MimePart> mimePartList = new List<MimePart>();

                
                if (attachments != null && attachments.Count > 0)
                {
                    for (int i = 0; i < attachments.Count; i++)
                    {
                        MimePart attachment = new MimePart("image", "jpg")
                        {
                            Content = new MimeContent(new MemoryStream(attachments[i]), ContentEncoding.Default),
                            ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                            ContentTransferEncoding = ContentEncoding.Base64,
                            FileName ="pic"+(i+1)+".jpg"
                        };

                        mimePartList.Add(attachment);
                    }
                   
                }

                //文本消息
                // create our message text, just like before (except don't set it as the message.Body)
                var body = new TextPart("plain")
                {
                    Text = message
                };



                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");

                //加入文本
                multipart.Add(body);

                //加入附件
                foreach (var item in mimePartList)
                {
                    multipart.Add(item);
                }

                // now set the multipart/mixed as the message body
                emailMessage.Body = multipart;

                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(host, 25, SecureSocketOptions.None).ConfigureAwait(false);
                    await client.AuthenticateAsync(emailUserName, emailPassword);
                    await client.SendAsync(emailMessage).ConfigureAwait(false);
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }

                return true;
            }
            catch (Exception ex)
            {             
                Common.Helper.Logger.Info($"BatchSendEmailAsync-发送邮件异常,异常信息{ex.ToString()}");
                return false;
            }
        }

        #endregion
    }
}
